package brushexercises.day61;

/**
 * @Describe : 28. 实现 strStr()
 * @Author : sunzhenning
 * @Since : 2022/8/2 16:12
 */
public class NO_28_ImplementStrstr {

    public static void main(String[] args) {
        NO_28_ImplementStrstr implementStrstr = new NO_28_ImplementStrstr();
        String haystack = "hello";
        String needle = "ll";
        int ans = implementStrstr.strStr(haystack, needle);
        System.out.println(ans);
    }

    /**
     * 双指针思想:
     * @param haystack
     * @param needle
     * @return
     */
    public int strStr(String haystack, String needle) {
        //默认的情况 n > m
        int n = haystack.length();
        int m = needle.length();
        //循环n-m次就可以了
        for(int i=0;i<=n-m;i++){
            //haystack的指针
            int a = i;
            //needle的指针
            int b = 0;
            while (b < m && haystack.charAt(a) == needle.charAt(b)){
                a++;
                b++;
            }
            if(b == m){
                return i;
            }
        }
        return -1;
    }
}
